package com.stylefeng.guns.rest.modular.wz.api.v1;


import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.AsyncService;
import com.stylefeng.guns.rest.modular.wz.controller.WzShareService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdminServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 管理端模块
 * @author ruiyifeng
 * @since 2018-04-26
 */
@RestController
@RequestMapping("/wz/api/v1/wzAdmin/")
public class WzAdminApi extends ApiBaseController{
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private WzPrizeMapper prizeMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private WzAdminServiceImpl adminService;

    /**
     * 待审核周边店铺页面
     */
    @PostMapping("advMapCheckList")
    public Res advMapCheckList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        List<Map<String,Object>>  advMapList = advMapMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdvMap>().eq("type",EnWzAdvMap.TYPE_Adv.getIndex()).in("status",new Integer[]{EnWzAdvMap.STATUS_Checking.getIndex(),EnWzAdvMap.STATUS_RelesseEditors.getIndex()}));
        for (Map<String, Object> map : advMapList) {
            map.put("advMapDetail", "");
            if (StringUtils.isNotBlank(map.get("targetId").toString())) {
                Long targetId = Long.parseLong(map.get("targetId").toString());
                WzAdvMap targetAdvMap = advMapMapper.selectById(targetId);
                map.put("name", targetAdvMap.getName());
                map.put("avatarUrl", targetAdvMap.getAvatarUrl());
                map.put("subtitle", targetAdvMap.getSubtitle());
                map.put("merchantTel", targetAdvMap.getMerchantTel());
                map.put("shareLink", targetAdvMap.getShareLink());
                map.put("logo", targetAdvMap.getLogo());
            }
        }
        return Res.success(paramMap.data(advMapList));
    }

    /**
     * 周边店铺提交审核
     */
    @PostMapping("advMapCheck")
    public Res advMapCheck(@RequestBody ParamMap paramMap, HttpServletResponse response) throws Exception{
        Long advMapId = paramMap.getLongMisValid("advMapId");
        int checkResult = paramMap.getIntMisValid("checkResult");
        String checkRemark = paramMap.getStrMisValid("checkRemark");
        String advMapCategoryFirst = paramMap.getStrValid("advMapCategoryFirst");
        String advMapCategorySecond = paramMap.getStrValid("advMapCategorySecond");
        String advMapCategoryThird = paramMap.getStrValid("advMapCategoryThird");

        //权限判断
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser adminUser = cacheService.user(userCode);
        List<SysUser> sysUser = sysUserMapper.selectList(new EntityWrapper<SysUser>().eq("phone", adminUser.getAccount()).eq("status",1));
        if (sysUser.get(0).getRoleid().equals("10") || sysUser.get(0).getRoleid().equals("7")) {
        }else{
            return Res.fail("没有审核权限!");
        }

        WzAdvMap advMap = advMapMapper.selectById(advMapId);
        advMap.setAdvMapCategoryFirst(advMapCategoryFirst);
        advMap.setAdvMapCategorySecond(advMapCategorySecond);
        advMap.setAdvMapCategoryThird(advMapCategoryThird);
        WzUser wzUser = cacheService.user(advMap.getUserCode());
        if(checkResult == EnWzCheckRecord.CHECK_RESULT_SUCCESS.getIndex()){//审核通过
            //用户设置为有地图用户
            wzUser.setHasAdvMap(EnWzUser.HSA_ADV_MAP_TRUE.getIndex());
            int status = advMap.getStatus();
            boolean r = adminService.saveAdvMapCheckSuccess(advMap,wzUser);
            if(r){
                if(advMap.getPublishingType() == 1){
                    //异步发送结果
                    WzUserMessage userMessage = new WzUserMessage();//用户消息
                    userMessage.setCreateTime(new Date());
                    userMessage.setType(EnWzUser.Message_Type_AdvMap_Release.getIndex());//地图广告审核
                    userMessage.setUserCode(advMap.getUserCode());
                    userMessage.setJumpTarget(advMap.getAdvMapId().toString());
                    if(status ==  EnWzAdvMap.STATUS_Checking.getIndex()){
                        userMessage.setContent("尊敬的用户，您有一个周边店铺发布成功，请注意查看!");
                    }else if(status ==  EnWzAdvMap.STATUS_RelesseEditors.getIndex()){
                        userMessage.setContent("尊敬的用户，您有一个周边店铺修改成功，请注意查看!");
                        if(Consts.dev.equals("true")){
                            sendPost(Consts.localhost + "/wz/api/v1/cancleCache/advMap","");
                        }else{
                            sendPost("http://wzapp.50waizhuan.com/wz/api/v1/cancleCache/advMap","");
                        }
                    }
                    userMessage.setTitle("周边店铺发布成功");
                    asyncService.checkUserAdv(userMessage,wzUser,userMessage.getType(),null);
                }
                return Res.success();
            }
        }else if(checkResult == EnWzCheckRecord.CHECK_RESULT_FAIL.getIndex()){//审核驳回
            advMap.setRejectRemark(checkRemark);
            boolean r = adminService.saveAdvMapCheckFail(advMap,wzUser);
            //异步发送结果
            if(r){
                //异步发送结果
                WzUserMessage userMessage = new WzUserMessage();//用户消息
                userMessage.setCreateTime(new Date());
                userMessage.setType(EnWzUser.Message_Type_AdvMap_Release.getIndex());//地图广告审核
                userMessage.setUserCode(advMap.getUserCode());
                userMessage.setJumpTarget(advMap.getAdvMapId().toString());
                if(advMap.getStatus() ==  EnWzAdvMap.STATUS_Add_Reject.getIndex()){
                    userMessage.setContent("尊敬的用户，您有一个周边店铺审核驳回,驳回原因:"+checkRemark+"，发布金额已退回。");
                }else if(advMap.getStatus() ==  EnWzAdvMap.STATUS_Edit_Reject.getIndex()){
                    userMessage.setContent("尊敬的用户，您有一个周边店铺修改审核驳回,驳回原因:"+checkRemark+"。");
                }
                userMessage.setTitle("周边店铺审核驳回");
                asyncService.checkUserAdv(userMessage,wzUser,userMessage.getType(),null);
                return Res.success();
            }
        }
        return Res.fail();
    }

    /**
     * 全部广告红包发布记录
     */
    @PostMapping("totalAdvReleaseRecords")
    public Res advReleaseRecords(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);
        List<SysUser> sysUser = sysUserMapper.selectList(new EntityWrapper<SysUser>().eq("phone",user.getAccount().toString()));
        String sql = "cover_url As coverUrl,adv_id As advId,release_time As releaseTime,status,subtype";
        List<Map<String,Object>> advs = new ArrayList<>();
        if(sysUser.get(0).getRoleid().equals("10") || sysUser.get(0).getRoleid().equals("8") || sysUser.get(0).getPhone().equals("13815002371")){
            advs = advMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdv>().setSqlSelect(sql).ge("status",EnWzAdv.STATUS_RELEASE_no.getIndex()).orderBy("release_time",false));
        }else{
            advs = advMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdv>().setSqlSelect(sql).ge("status",EnWzAdv.STATUS_RELEASE_no.getIndex()).eq("admin_name",sysUser.get(0).getName()).orderBy("release_time",false));
        }
        paramMap.put("list",advs);
        return Res.success(paramMap);
    }

    /**
     * 待审核广告页面
     */
    @PostMapping("advCheck.index")
    public Res advCheckIndex(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        //待审核广告
        String sql = "nick_name As nickName,expense As totalReward,avatar_url As avatarUrl,adv_id As advId,title,cover_url As coverUrl,subtype";
        List<Map<String,Object>>  advList = advMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdv>().setSqlSelect(sql).in("subtype",new Integer[]{EnWzAdv.SUBTYPE_ADV.getIndex(),EnWzAdv.SUBTYPE_user_redPacket.getIndex(),EnWzAdv.SUBTYPE_Screen_Adv.getIndex()}).eq("status",EnWzAdv.STATUS_WaitCheck.getIndex()));
        return Res.success(paramMap.data(advList));
    }

    /**
     * 待审核奖品页面
     */
    @PostMapping("prizeCheck.index")
    public Res prizeCheckIndex(){
        List<Map<String,Object>> prizeList = new ArrayList<>();
        String prizeSql = "prize_id As prizeId,title,subtitle,cover_url As coverUrl,label,exchange_amount As exchangeAmount";
        List<Map<String,Object>>  prizeLists = prizeMapper.selectMaps(new EntityWrapper<WzPrize>().setSqlSelect(prizeSql).eq("status", EnWzPrize.STATUS_WaitCheck.getIndex()).eq("type",EnWzPrize.TYPE_Prize_Coupon.getIndex()).orderBy("create_time",false));
        for(Map<String,Object>  map:prizeLists){
            Map m = new HashMap();
            m.put("prize",map);
            //奖品获奖名单列表
            List list = new ArrayList();
            m.put("prizeWinners",list);
            prizeList.add(m);
        }
        return Res.success(prizeList);
    }

    /**
     * 奖券详情
     */
    @PostMapping("couponDetail")
    public Res couponDetail(@RequestBody ParamMap paramMap){
        String prizeId = paramMap.getStrMisValid("prizeId");
        //礼券
        String sql = "coupon_id As couponId,adv_map_id As advMapId,rule,benefit,type,subtype,begin_time As beginTime,end_time As endTime,pic";
        List<Map<String,Object>>  couponList = couponMapper.selectMaps(new EntityWrapper<WzCoupon>().setSqlSelect(sql).eq("prize_id",prizeId));
        Map<String,Object> coupon=couponList.get(0);
        WzAdvMap advMap=cacheService.advMap(Long.parseLong(coupon.get("advMapId").toString()));
        coupon.put("name",advMap.getName());
        coupon.put("merchantTel",advMap.getMerchantTel());
        coupon.put("longitude",advMap.getLongitude());
        coupon.put("latitude",advMap.getLatitude());
        coupon.put("merchantAddress",advMap.getMerchantFullAddress());
        paramMap.putAll(coupon);
        return Res.success(paramMap);
    }

    /**
     * 审核奖品
     */
    @PostMapping("prizeCheck")
    @Transactional
    public Res prizeCheck(@RequestBody ParamMap paramMap){
        String prizeId = paramMap.getStrMisValid("prizeId");//奖品id
        int checkResult = paramMap.getIntMisValid("checkResult");

        //权限判断
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser adminUser = cacheService.user(userCode);
        List<SysUser> sysUser = sysUserMapper.selectList(new EntityWrapper<SysUser>().eq("phone", adminUser.getAccount()).eq("status",1));
        if (sysUser.get(0).getRoleid().equals("10") || sysUser.get(0).getRoleid().equals("7")) {
        }else{
            return Res.fail("没有审核权限!");
        }

        //奖品状态修改
        WzPrize prize = prizeMapper.selectById(prizeId);
        if(checkResult == EnWzCheckRecord.CHECK_RESULT_FAIL.getIndex()){//审核驳回
            prize.setStatus(EnWzPrize.STATUS_REJECT.getIndex());
            int r = prizeMapper.updateAllColumnById(prize);
            if(r > 0){
                return Res.success();
            }
        }else if(checkResult == EnWzCheckRecord.CHECK_RESULT_SUCCESS.getIndex()){//审核通过
            prize.setStatus(EnWzPrize.STATUS_SUCCESS.getIndex());
            List<WzCoupon> coupons = couponMapper.selectList(new EntityWrapper<WzCoupon>().eq("prize_id",prize.getPrizeId().toString()));
            coupons.get(0).setStatus(2);
            int r = prizeMapper.updateAllColumnById(prize);
            if(r > 0){
                r = couponMapper.updateById(coupons.get(0));
                if(r > 0){
                    return Res.success();
                }
            }
        }else{
            return Res.fail("审核结果参数不对!");
        }
        return Res.success();
    }


    /**
     * 审核广告
     */
    @PostMapping("advCheck.check")
    public Res advCheck(@RequestBody ParamMap paramMap){
        int checkResult = paramMap.getIntMisValid("checkResult");
        int type = paramMap.getIntMisValid("type");

        //权限判断
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser adminUser = cacheService.user(userCode);
        List<SysUser> sysUser = sysUserMapper.selectList(new EntityWrapper<SysUser>().eq("phone", adminUser.getAccount()).eq("status",1));
        if (sysUser.get(0).getRoleid().equals("10") || sysUser.get(0).getRoleid().equals("7")) {
        }else{
            return Res.fail("没有审核权限!");
        }

        if(type == EnWzAdv.SUBTYPE_ADV.getIndex()){ //广告审核
            String advId = paramMap.getStrMisValid("advId");
            WzAdv adv = advMapper.selectById(advId);
            //更新广告状态
            if(adv.getStatus() == EnWzAdv.STATUS_WaitCheck.getIndex()){
                if(checkResult == EnWzCheckRecord.CHECK_RESULT_FAIL.getIndex()){//审核驳回
                    adv.setStatus(EnWzAdv.STATUS_REJECT.getIndex());
                }else if(checkResult == EnWzCheckRecord.CHECK_RESULT_SUCCESS.getIndex()){//审核通过
                    adv.setStatus(EnWzAdv.STATUS_SUCCESS.getIndex());
                }else{
                    return Res.fail("审核结果参数不对!");
                }
                int r = advMapper.updateById(adv);
                if(r > 0){
                    return Res.success();
                }
            }
        }
        return Res.fail();
    }

    public static String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
